package com.jspgou.cms.action.front;

import static com.jspgou.common.page.SimplePage.cpn;
import static com.jspgou.cms.Constants.MEMBER_SYS;
import static com.jspgou.cms.Constants.STORE_SYS;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.CookieUtils;
import com.jspgou.common.web.ResponseUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;
import com.jspgou.cms.entity.Gift;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.manager.GiftMng;
import com.jspgou.cms.manager.GiftSvcMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;

@Controller
public class MyGiftAct {
	private static final Logger log = LoggerFactory.getLogger(MyGiftAct.class);
	
	private static final String SHOPPING_CART = "tpl.shoppingCart";
	
	@RequestMapping(value = "/my_gift.jspx", method = RequestMethod.GET)
	public String list(Integer pageNo,HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		Pagination pagination =giftMng.getPageGift(cpn(pageNo), CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("pageNo", pageNo);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,
				"tpl.myGift"), request);
	}
	
	@RequestMapping(value = "/fetchGift.jspx")
	public void fetchGift(Long giftId,Integer giftNumb,HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		Gift gift=giftMng.updateByGiftnumb(giftId, giftNumb,member.getId());
		if(gift==null){
			ResponseUtils.renderJson(response, "你的积分不足！");
			return;
		}
		giftSvcMng.addToCart(giftId,giftNumb, true,member, web, request, response);
		ShopFrontHelper.setCommonData(request, model, web);
        ResponseUtils.renderJson(response, "兑换礼品成功！");	
		
	}

	@Autowired
	private GiftMng giftMng;
	@Autowired
	private GiftSvcMng giftSvcMng;

}
